package cn.tedu.myweb.myweb.Controller;

import java.io.IOException;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.tedu.myweb.myweb.util.HttpClient;


@Controller
public class ForwardController {
	@Value("${myweb.tedurl}")
	private String Tedurl;
	@Value("${myweb.myurl}")
	private String Myurl;
	
	@GetMapping("get")
	public String Forward(String url) {
		if(url == null) {
			return "handler_error";
		}
		int index = url.indexOf(".");
		if(index != -1){
			String name = url.substring(index);
			if(name.equals(".ts")) {
				return "getts";
			}else if(name.equals(".m3u8")) {
				return "getm3u8";
			}else if(name.equals(".key")){
				return "getkey";
			}
		}
		return "handler_error";
	}
	
	@ResponseBody
	@GetMapping(value="/getm3u8",produces="audio/x-mpegurl")
	public String getm3u8(String url) throws IOException {
		byte[] data = HttpClient.getData(url,Tedurl);
		
		String m3u8 = HttpClient.byteArrToString(data).replaceAll(Tedurl, Myurl);
		//String myClass = url.substring(0, url.indexOf("/"));
		return m3u8;
	}
	@ResponseBody
	@GetMapping(value="/getts",produces="application/x-linguist")
	public byte[] getts(String url) throws IOException {
		return HttpClient.getData(url,Tedurl);
	}
	@ResponseBody
	@GetMapping(value="/getkey",produces="text/plain")
	public byte[] getkey(String url) throws IOException {
		return HttpClient.getData(url,Tedurl);
	}
	@ResponseBody
	@GetMapping("handler_error")
	public String handler_error() {
		return "请求错误!";
	}
	
	
}
